package com.zyp.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * @author zhangyanping
 */
public class MsgHandler implements NIOHandler {
    private final SocketChannel channel;
    private final SelectionKey selectionKey;


    public MsgHandler(SocketChannel channel, SelectionKey selectionKey) {
        this.channel = channel;
        this.selectionKey = selectionKey;
    }

    @Override
    public synchronized void handle() {
        try {
            byte[] msg = new byte[1024];
            ByteBuffer byteBuffer = ByteBuffer.wrap(msg);
            int length = channel.read(byteBuffer);
            if(length==-1){
                selectionKey.cancel();
                channel.close();
                return;
            }
                System.out.println("收到消息：" + new String(msg));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
